# Author: Damian 'Rush' Kaczmarek
# License: MIT

package Auth;
use base Module;
use strict;

my %allowlist;

foreach my $allowed (split(/,/, Config::get('allowed'))) {
	$allowlist{$allowed} = 1;

}

my %execlist;

# run_authed - run some command only if a nickname is authenticated in the NickServ irc service
# @_[0]    - nickname of the caller
# @_[1]    - function reference
# @_[2...] - arguments to the function reference
sub run_authed
{
	my $nick = $_[0];
	if (!exists($allowlist{$nick})) {
		Core::send_msg($nick . ": Co wolno wojewodzie to nie Tobie smrodzie! :>")
		  ;    # Yep, screw off if not privileged! =]
	}
	shift;

	# Store the command and arguments
	if (exists($execlist{$nick})) {
		push(@{$execlist{$nick}}, @_);
	}
	else {
		$execlist{$nick} = [@_];
	}
	Core::send_priv("nickserv", "status " . $nick);
}

sub on_notice
{
	my $nick   = $_[0];
	my $notice = $_[1];
	if ($nick =~ m/^nickserv/i) {    # Accept only nickserv notices
		my @args = split(/ /, $notice);
		if ($args[0] =~ /STATUS/) {    # STATUS is an answer to nickserv authentication check query
			if ($args[2] == 2 || $args[2] == 3) {    # 2 and 3 signify proper rights to the nick

				$nick = $args[1];
				if (exists($execlist{$nick})) {
					my $elem;
					foreach $elem (@{execlist {$nick}}) {   # Now iterate through all saved commands
						@args = @{$elem};
						my $func = $args[0];
						shift(@args);

						print "Running auth!\n";
						$func->(@args);                 # Finally run the code!
					}
					undef($execlist{$nick});
				}
			}
		}
	}
}
1;
